package com.glink.gateway.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : qiushaoshan
 * @create 2024/6/26 9:49
 */
@UtilityClass
public class HttpUtils {

    /**
     * 修改前端传的参数
     */
    public SortedMap<String, Object> getRequestParam(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        String query = uri.getQuery();
        if (StringUtils.isNotBlank(query)) {
            SortedMap<String, Object> result = new TreeMap<>();
            String[] split = query.split("&");
            for (String str : split) {
                String[] params = str.split("=");
                if(params.length == 2) {
                    Object oldValue = result.get(params[0]);
                    Object newValue = params[1];
                    // 这里的判断主要用于解决类型问题
                    StringBuilder targetValue = new StringBuilder();
                    if(oldValue!=null){
                        targetValue.append(oldValue).append(StrUtil.COMMA);
                    }
                    targetValue.append(newValue);
                    result.put(params[0], targetValue);
                }
            }
            return result;
        }
        return new TreeMap<>();
    }


    /**
     * 获取指定请求头的值
     * @param request
     * @param headerKey
     * @return
     */
    public String getHeaderVal(ServerHttpRequest request,String headerKey){
        List<String> strings = request.getHeaders().get(headerKey);
        if(CollUtil.isNotEmpty(strings)){
            assert strings != null;
            return strings.get(0);
        }else {
            return null;
        }
    }

}

